﻿using System;
using Casamiel.Domain.Response;
using Casamiel.Domain;
using MediatR;
using Microsoft.Extensions.Options;
using Casamiel.Common;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Data;

namespace Casamiel.Application.Commands
{
	/// <summary>
	/// 
	/// </summary>
	public sealed class CouponForwardCommandHandler : BaseCommandHandler, IRequestHandler<CouponForwardCommand, BaseResult<MemberCouponGive>>
	{
		private readonly IMemberRepository _memberRepository;
		private readonly IMemberCouponRepository _memberCouponRepository;
		private readonly IMemberCouponGiveRepository _memberCouponGiveRepository;
		private readonly ICasaMielSession _session;

		/// <summary>
		/// 
		/// </summary>
		/// <param name="memberRepository"></param>
		/// <param name="memberCouponRepositor"></param>
		/// <param name="netICService"></param>
		/// <param name="httpClientFactory"></param>
		/// <param name="settings"></param>
		/// <param name="casaMielSession"></param>
		public CouponForwardCommandHandler(IMemberRepository memberRepository, IMemberCouponRepository memberCouponRepositor, INetICService netICService,
			IHttpClientFactory httpClientFactory, IOptionsSnapshot<CasamielSettings> settings, ICasaMielSession casaMielSession, IMemberCouponGiveRepository
			memberCouponGiveRepository) : base(netICService, httpClientFactory, settings)

		{
			_memberRepository = memberRepository;
			_memberCouponRepository = memberCouponRepositor;
			_session = casaMielSession;
			_memberCouponGiveRepository = memberCouponGiveRepository;
		}

		public async Task<BaseResult<MemberCouponGive>> Handle(CouponForwardCommand request, CancellationToken cancellationToken)
		{
			if (request is null) {
				throw new ArgumentNullException(nameof(request));
			}

			var entity = await _memberRepository.FindAsync<ICasaMielSession>(request.Mobile).ConfigureAwait(false);
			if (entity == null) {
				return new BaseResult<MemberCouponGive>(null, 999, "会员不存在");
			}
			var coupon = await _memberCouponRepository.GetKeyAsync<ICasaMielSession>(request.MCID).ConfigureAwait(false);
			if (coupon == null || coupon.MID != entity.ID) {
				return new BaseResult<MemberCouponGive>(null, 999, "券不存在");
			}

			if (coupon.GiveStatus !=0 && coupon.GiveStatus != -1) {
				string msg="";
				switch (coupon.GiveStatus) {
					case 1:
						msg = "不可赠送";
						break;
					
					case -2:
						msg = "券已经赠送";
						break;
				}
				return new BaseResult<MemberCouponGive>(null, 999, msg);
			}

			var forwardcode = Guid.NewGuid().ToString();// Common.Utilities.SecurityUtil.EncryptText($"{DateTime.Now.Ticks}-{request.MCID}", entity.Mobile);
			var coupongive = new MemberCouponGive {
				MCID = request.MCID,
				ForwardCode= forwardcode,
				Message = request.Message,
				Productname = coupon.Productname,
				Status = 0,
				MID = entity.ID,
				CreateTime=DateTime.Now,
				

			};
			bool s = false;
			using (var uow = _session.UnitOfWork(IsolationLevel.Serializable))
			{
				await _memberCouponGiveRepository.SaveAsync(coupongive, uow).ConfigureAwait(false);
				s=await _memberCouponRepository.UpdateCouponGiveStatusAsnync(coupon,-1, uow).ConfigureAwait(false);
				if (s) {
					uow.Commit();
				} else {
					uow.Rollback();
				}
			}
			if (s) {
				return new BaseResult<MemberCouponGive>(coupongive, 0, "");

			}
			return new BaseResult<MemberCouponGive>(null, 999, "请重试");
		}
	}
}
